import 'package:flutter/material.dart';
import 'package:flutterapp900sui/models/listModelItems.dart';

typedef FilterDidSelectedHandleBlock = Future Function(int index);

//  筛选框组件
class FilterMenuView extends StatefulWidget {

  final List<ListCellItem> items;
  final double height;


  final FilterMenuViewController menuViewController;
  final FilterDidSelectedHandleBlock onSelectedBlock;

  FilterMenuView({
    Key key,
    this.items,
    this.height = 44,
    this.menuViewController,
    this.onSelectedBlock
  });

  @override
  _FilterMenuViewState createState() => _FilterMenuViewState();
}

class _FilterMenuViewState extends State<FilterMenuView>{

  double _screenWidth;
  int _menuCount;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    widget.menuViewController.hideCompleteHandleBlock = (){
      //  处理当前组件的状态项
      widget.items.forEach((element) {
        element.isSelected = false;
      });
      setState(() {});
    };
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    MediaQueryData mediaQuery = MediaQuery.of(context);
    _screenWidth = mediaQuery.size.width;
    _menuCount = widget.items.length;

    return Positioned(
        child: Container(
          height: widget.height,
          color: Colors.white,
          child: GridView.count(
            physics: NeverScrollableScrollPhysics(),
            crossAxisCount: _menuCount,
            childAspectRatio: (_screenWidth / _menuCount) / widget.height,
            children: widget.items.map<Widget>((e){
              return _buildMenuItem(e);
            }).toList(),
          ),
        )
    );
  }

  //  创建每个FilterMenu的item
  _buildMenuItem(ListCellItem item){
    int index = widget.items.indexOf(item);
    int currentIndex = widget.menuViewController.currentIndex;
    return GestureDetector(
      onTap: (){
        //  给控制器设置当前的选择index

        //  处理当前组件的状态项
        widget.items.forEach((element) {
          element.isSelected = false;
        });
        //  执行筛选框的回调事件
        if(widget.onSelectedBlock != null){
          widget.onSelectedBlock(index);
        }

        if(index == currentIndex){
          if(widget.menuViewController.isShow){
            widget.menuViewController.hide();
          }else{
            widget.menuViewController.show(index);
            widget.items[index].isSelected = true;
          }
        }else{
          if(widget.menuViewController.isShow){
            widget.menuViewController.hide(isShowHideAnimation: false);
          }
          widget.menuViewController.show(index);
          widget.items[index].isSelected = true;
        }
        setState(() {});
      },
      child: Container(
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Expanded(child:
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Flexible(
                    child: Text(
                      item.title,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,)
                  ),
                  Icon(item.isSelected ? Icons.arrow_drop_up : Icons.arrow_drop_down,
                  color: item.isSelected ? Colors.blue : Colors.black87,)
                ],
              )
            ),
            index == widget.items.length - 1 ? Container() : Container(
              height: 24,
              decoration: BoxDecoration(
                border: Border(
                  right: BorderSide(color: Colors.grey)
                )
              ),
            )
          ],
        ),
      ),
    );
  }
}


//  筛选框下的选项卡容器
class FilterMenuPannelView extends StatefulWidget {

  final List<FilterMenuPannelItem> items;
  final FilterMenuViewController menuViewController;
  final int animationDuration;  //动画时间
  final Color maskColor;        //遮罩层的颜色

  FilterMenuPannelView({
    Key key,
    @required this.menuViewController,
    @required this.items,
    this.animationDuration = 300,
    this.maskColor = const Color.fromRGBO(0, 0, 0, 0.5)
  }) : super(key: key);

  @override
  _FilterMenuPannelViewState createState() => _FilterMenuPannelViewState();
}

class _FilterMenuPannelViewState extends State<FilterMenuPannelView> with SingleTickerProviderStateMixin{

  Animation<double> _animation;
  AnimationController _animationController;

  bool _isShowMask = false;
  int _currentIndex;        //  当前显示度筛选index
  double _pannelHeight;     //  内容的高度
  double _maskColorOpacity; //  遮罩层的透明度

  @override
  void initState(){
    super.initState();
    widget.menuViewController.addListener(_showPannelWidget);
    _animationController = new AnimationController(duration: Duration(milliseconds: widget.animationDuration),vsync: this);
  }
  @override
  void dispose() {
    // TODO: implement dispose
    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);

    _animation = new Tween(begin: 0.0, end: _pannelHeight).animate(_animationController)
      ..addListener(_animationListener)
      ..addStatusListener(_animationStatusListener);

    widget.menuViewController.removeListener(_showPannelWidget);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build

    int index = widget.menuViewController.currentIndex;
    if(index >= widget.items.length){
      return Container();
    }

    return Positioned(
        width: MediaQuery.of(context).size.width,
        top: 44,
        child: Column(
          children: [
            Container(
              color: Colors.white,
              height: _animation == null ? 0 : _animation.value,
              child: widget.items[index].itemWidget,
            ),
            _buildMask()
          ],
        ));
  }

  Widget _buildMask(){

    if(_isShowMask){
      return GestureDetector(
        onTap: (){
          widget.menuViewController.hide();
        },
        child: Container(
            width: MediaQuery.of(context).size.width,
            height: MediaQuery.of(context).size.height,
            color: widget.maskColor.withOpacity(_maskColorOpacity)
        ),
      );
    }
    else {
      return Container(height: 0,);
    }
  }

  //  监听事件方法
  void _showPannelWidget(){
    _currentIndex = widget.menuViewController.currentIndex;
    if(_currentIndex >= widget.items.length || widget.items[_currentIndex] == null){
      return;
    }

    if(!_isShowMask){
      _isShowMask = true;
    }

    _pannelHeight = widget.items[_currentIndex].itemHeight;

    _animation?.removeListener(_animationListener);
    _animation?.removeStatusListener(_animationStatusListener);
    _animation = new Tween(begin: 0.0, end: _pannelHeight).animate(_animationController)
      ..addListener(_animationListener)
      ..addStatusListener(_animationStatusListener);

    if(widget.menuViewController.isShow){
      _animationController.forward();
    }else if (widget.menuViewController.isShowHideAnimation){
      _animationController.reverse();
    }
    else{
      _animationController.value = 0;
    }
  }

  //  动画执行【透明度】
  void _animationListener(){
    var heightScale = _animation.value / _pannelHeight;
    _maskColorOpacity = widget.maskColor.opacity * heightScale;
    setState(() {});
  }
  //  动画状态监听
  void _animationStatusListener(AnimationStatus status){
    switch(status){
      case AnimationStatus.dismissed:
        _isShowMask = false;
        break;
      case AnimationStatus.forward:
        break;
      case AnimationStatus.reverse:
        break;
      case AnimationStatus.completed:
        break;
    }
  }
}

class FilterMenuPannelItem{
  final Widget itemWidget;
  final double itemHeight;
  FilterMenuPannelItem({@required this.itemWidget, @required this.itemHeight});
}

//  筛选框的监听控制器
typedef FilterMenuViewControllerFinishedHandleBlock = void Function();

class FilterMenuViewController extends ChangeNotifier{
  double filterMenuHeight;
  int currentIndex = 0;
  bool isShow = false;
  bool isShowHideAnimation = false;

  FilterMenuViewControllerFinishedHandleBlock showCompleteHandleBlock;
  FilterMenuViewControllerFinishedHandleBlock hideCompleteHandleBlock;

  void show(int index){
    isShow = true;
    currentIndex = index;
    notifyListeners();

    if(showCompleteHandleBlock != null){
      showCompleteHandleBlock();
    }
  }

  void hide({bool isShowHideAnimation = true}){
    this.isShowHideAnimation = isShowHideAnimation;
    isShow = false;
    notifyListeners();

    if(hideCompleteHandleBlock != null){
      hideCompleteHandleBlock();
    }
  }
}


enum FilterOptionType {
  none,
  single,
  double,
  multiple
}

typedef FilterOptionDidSelectedHandleBlock = Future Function(List<ListCellItem> items);

//  筛选框的选项卡
class FilterOptionView extends StatefulWidget {

  final FilterOptionType type;
  final List<ListCellItem> optionItems;
  final FilterOptionDidSelectedHandleBlock onSelectedBlock;

  FilterOptionView({
    Key key,
    this.type = FilterOptionType.none,
    this.optionItems,
    this.onSelectedBlock
  });

  _FilterOptionViewState createState() => _FilterOptionViewState();
}

class _FilterOptionViewState extends State<FilterOptionView> {

  //  选择的cellItem
  ListCellItem _selectedCellItem = ListCellItem('');

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    _selectedCellItem = ListCellItem('');
    widget.optionItems.forEach((element) {
      if(element.isSelected){
        _selectedCellItem = element;
        return;
      }
    });

    switch(widget.type){
      case FilterOptionType.single:
        return _createSingleOptionView();
        break;
      case FilterOptionType.double:
        return _createDoubleOptionView();
        break;
      case FilterOptionType.multiple:
        return _createMultipleOptionView();
        break;
      default:
        return Container();
        break;
    }
  }

  Widget _createSingleOptionView(){
    return Container(
      child: ListView.separated(
        itemBuilder: (BuildContext context, int index){
          var item = widget.optionItems[index];
          return GestureDetector(child: ListTile(leading: Text(item.title, style: TextStyle(color: item.isSelected ? Colors.red : Colors.black87))),onTap: (){

            widget.optionItems.forEach((element) {
              element.isSelected = element == item ? true : false;
            });
            setState(() {});

            if(widget.onSelectedBlock != null){
              widget.onSelectedBlock([item]);
            }
            },);
          },
        separatorBuilder: (BuildContext context, int index) => Divider(height: 1.0,),itemCount: widget.optionItems.length,)
    );
  }

  Widget _createDoubleOptionView(){
    return Container(
      child: Row(
        children: [
          Container(
              width: 120,
              child: ListView.separated(
                  itemBuilder: (BuildContext context, int index){
                    var item = widget.optionItems[index];
                    return GestureDetector(child: ListTile(leading: Text(item.title, style: TextStyle(color: item.isSelected ? Colors.red : Colors.black87),)),onTap: (){
                      _selectedCellItem = item;
                      widget.optionItems.forEach((element) {
                        element.isSelected = element == item ? true : false;
                        if(!element.isSelected){
                          element.items.forEach((subElement) {
                            subElement.isSelected = false;
                          });
                        }
                      });
                      setState(() {});

                      if(widget.onSelectedBlock != null && _selectedCellItem.items.length == 0){
                        widget.onSelectedBlock([_selectedCellItem]);
                      }
                    },);
                    },
                  separatorBuilder: (BuildContext context, int index) => Divider(height: 1.0,),
                  itemCount: widget.optionItems.length)
          ),
          Container(
            width: 5,
          ),
          Expanded(
              child: Container(
                child: ListView.separated(
                    itemBuilder: (BuildContext context, int index){
                      var subItem = _selectedCellItem.items[index];
                      return GestureDetector(child: ListTile(leading: Text(subItem.title, style: TextStyle(color: subItem.isSelected ? Colors.red : Colors.black87),)),onTap: (){
                        _selectedCellItem.items.forEach((element) {
                          element.isSelected = element == subItem ? true : false;
                        });
                        setState(() {});

                        if(widget.onSelectedBlock != null){
                          widget.onSelectedBlock([_selectedCellItem,subItem]);
                        }
                      },);
                      },
                    separatorBuilder: (BuildContext context, int index) => Divider(height: 1.0,),
                    itemCount: _selectedCellItem.items.length ?? 0),
              )
          )
        ],
    ),);
  }

  Widget _createMultipleOptionView(){
    return Container(
      color: Colors.yellow,
    );
  }
}